package com.etc.dysys.admin.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.dysys.admin.service.AdminService;
import com.etc.dysys.admin.service.impl.AdminServiceImpl;
import com.etc.dysys.entity.Admin;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/Admin.action")
public class AdminServlet extends HttpServlet {
	
	private AdminService as = new AdminServiceImpl();
	private static final long serialVersionUID = 1L;
		
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op="login";
		if(request.getParameter("op")!=null) {
			op=request.getParameter("op");
		}
		if(op.equals("login")) {
			doLogin(request,response);
		}if(op.equals("exit")) {
			doExit(request,response);
		}
	}
	
	protected void doExit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(); 
		//清除记录
		session.invalidate();
		response.sendRedirect("admin/login.jsp");
	}
	
    /**
     * 查询单个admin（登录校验）
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
	protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String adminName = request.getParameter("adminName");
		String adminPwd = request.getParameter("adminPwd");
		
		Admin u = new Admin(adminName,adminPwd);
		Admin admin = as.findAdmin(u);

		if (admin != null) {
			// 将用户信息存储在session中
			HttpSession session = request.getSession();
			session.setAttribute("admin", admin);
			response.sendRedirect("admin/index.jsp");
		} else {
			
			response.sendRedirect("admin/login.jsp");

		}
		
	}
	
	
	
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}